package top.zhangjianyong.accesslog.utils;

import java.util.Date;

/**
 * id生成器
 *
 * @author zhangjianyong
 * @since 2024/7/22 下午3:13
 */
public class IdWorker {

    /* Because the first bit in binary is negative if it is 1, but the IDS we generate are all positive, so the first bit is 0. */

    // 机器ID  2进制5位  32位减掉1位 31个
    private final long workerId;
    // 机房ID 2进制5位  32位减掉1位 31个
    private final long dataCenterId;
    // 代表一毫秒内生成的多个id的最新序号  12位 4096 -1 = 4095 个
    private long sequence;
    // 设置一个时间初始值    2^41 - 1   差不多可以用69年
    private final static long timeInit = 1590575266950L;
    // 5位的机器id
    private final static long workerIdBits = 5L;
    // 5位的机房id
    private final static long dataCenterIdBits = 5L;
    // 每毫秒内产生的id数 2 的 12次方
    private final static long sequenceBits = 12L;
    // 这个是二进制运算，就是5 bit最多只能有31个数字，也就是说机器id最多只能是32以内
    private final static long maxWorkerId = ~(-1L << workerIdBits);
    // 这个是一个意思，就是5 bit最多只能有31个数字，机房id最多只能是32以内
    private final static long maxDataCenterId = ~(-1L << dataCenterIdBits);

    private final static long workerIdShift = sequenceBits;
    private final static long dataCenterIdShift = sequenceBits + workerIdBits;
    private final static long timestampLeftShift = sequenceBits + workerIdBits + dataCenterIdBits;
    private final static long sequenceMask = ~(-1L << sequenceBits);
    // 记录产生时间毫秒数，判断是否是同1毫秒
    private long lastTimestamp = -1L;

    public IdWorker(long workerId, long dataCenterId, long sequence) {
        // 检查机房id和机器id是否超过31 不能小于0
        if (workerId > maxWorkerId || workerId < 0) {
            throw new IllegalArgumentException(
                    String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
        }

        if (dataCenterId > maxDataCenterId || dataCenterId < 0) {
            throw new IllegalArgumentException(
                    String.format("dataCenter Id can't be greater than %d or less than 0", maxDataCenterId));
        }
        this.workerId = workerId;
        this.dataCenterId = dataCenterId;
        this.sequence = sequence;
    }

    // 这个是核心方法，通过调用 nextId() 方法，让当前这台机器上的 snowflake 算法程序生成一个全局唯一的id
    public synchronized long nextId() {
        // 这儿就是获取当前时间戳，单位是毫秒
        long timestamp = timeGen();
        if (timestamp < lastTimestamp) {
            System.err.printf(
                    "clock is moving backwards. Rejecting requests until %d.", lastTimestamp);
            throw new RuntimeException(
                    String.format("Clock moved backwards. Refusing to generate id for %d milliseconds",
                            lastTimestamp - timestamp));
        }

        // 下面是说假设在同一个毫秒内，又发送了一个请求生成一个id
        // 这个时候就得把 sequence 序号给递增1，最多就是 4096
        if (lastTimestamp == timestamp) {
            // 这个意思是说一个毫秒内最多只能有4096个数字，无论你传递多少进来，
            //这个位运算保证始终就是在4096这个范围内，避免你自己传递个sequence超过了4096这个范围
            sequence = (sequence + 1) & sequenceMask;
            //当某一毫秒的时间，产生的id数 超过4095，系统会进入等待，直到下一毫秒，系统继续产生ID
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0;
        }
        // 这儿记录一下最近一次生成id的时间戳，单位是毫秒
        lastTimestamp = timestamp;
        // 这儿就是最核心的二进制位运算操作，生成一个64bit的id
        // 先将当前时间戳左移，放到41 bit那儿；将机房id左移放到5 bit那儿；将机器id左移放到5 bit那儿；将序号放最后12 bit
        // 最后拼接起来成一个64 bit的二进制数字，转换成10进制就是个long型
        return ((timestamp - timeInit) << timestampLeftShift) |
                (dataCenterId << dataCenterIdShift) |
                (workerId << workerIdShift) | sequence;
    }

    /**
     * 当某一毫秒的时间，产生的id数 超过4095，系统会进入等待，直到下一毫秒，系统继续产生ID
     *
     * @param lastTimestamp lastTimestamp
     * @return long
     */
    private long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        // System.out.println("123");
        return timestamp;
    }

    //获取当前时间戳
    private long timeGen() {
        return System.currentTimeMillis();
    }

    /**
     * id时间小于当前时间
     *
     * @param id id
     * @return boolean
     * @author zhang
     * @date 15:25 2020/6/2 0002
     **/
    public static boolean isAfterNow(Long id) {

        if (id == null)
            return false;

        long l = (id >> timestampLeftShift) + timeInit;
        long time = new Date().getTime();
        return l > time;
    }

    /**
     * main 测试类
     *
     * @param args args
     */
    public static void main(String[] args) {
        IdWorker idWorker = new IdWorker(1, 1, 1);


        long id = idWorker.nextId();

        long l = (id >> timestampLeftShift) + timeInit;
        //long time = new Date().getTime();

        Date date = new Date(l);
        System.out.println(date);
        /*System.out.println(1 & 4596);
        System.out.println(2 & 4596);
        System.out.println(6 & 4596);
        System.out.println(6 & 4596);
        System.out.println(6 & 4596);
        System.out.println(6 & 4596);*/
// 机器ID  2进制5位  32位减掉1位 31个
      /*  long workerId = 1;
        // 机房ID 2进制5位  32位减掉1位 31个
        long dataCenterId = 1;
        // 代表一毫秒内生成的多个id的最新序号  12位 4096 -1 = 4095 个
        long sequence = 1;

        // 5位的机器id
        long workerIdBits = 5L;
        // 5位的机房id
        long dataCenterIdBits = 5L;
        // 每毫秒内产生的id数 2 的 12次方
        long sequenceBits = 12L;
        // 这个是二进制运算，就是5 bit最多只能有31个数字，也就是说机器id最多只能是32以内
        long maxWorkerId = ~(-1L << workerIdBits);
        System.out.println(maxWorkerId);
        // 这个是一个意思，就是5 bit最多只能有31个数字，机房id最多只能是32以内
        long maxDataCenterId = ~(-1L << dataCenterIdBits);
        System.out.println(maxDataCenterId);

        long workerIdShift = sequenceBits;
        System.out.println(workerIdShift);

        long dataCenterIdShift = sequenceBits + workerIdBits;
        System.out.println(dataCenterIdShift);

        long timestampLeftShift = sequenceBits + workerIdBits + dataCenterIdBits;

        System.out.println("timestampLeftShift," + timestampLeftShift);

        long timestamp = System.currentTimeMillis();
        timestamp = 9990574398926l;
        System.out.println(timestamp);
        long timeInit = 1590574398926L;

        long l1 = timestamp - timeInit;
        System.out.println(l1);
        System.out.println(Long.toBinaryString(l1));
        System.out.println(Long.toBinaryString(l1).length());
        long l = l1 << timestampLeftShift;
     *//*   System.out.println(l);
        System.out.println(Long.toBinaryString(  l));
        System.out.println(Long.toBinaryString(  l).length());*//*
        //System.out.println(Long.toBinaryString( l));

        long a = (l) |
                (dataCenterId << dataCenterIdShift) |
                (workerId << workerIdShift) | sequence;
        System.out.println(a);
        System.out.println(Long.toBinaryString(a));
        System.out.println(Long.toBinaryString(a).length());

        long max = Long.MAX_VALUE;
        System.out.println(Long.toBinaryString(max));

        long l2 = max / 1000 / 60 / 60 / 24 / 365;
        System.out.println(l2);*/

        //System.out.println(Long.toBinaryString(a));

    }
}



